package com.lagou.configuration;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dcwu5
 * @date 2020-05-23
 * @description
 */
public class MapperBuilder {

    private Configuration configuration;

    public MapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapper(InputStream resourceAsStream) throws DocumentException {
        Document document = new SAXReader().read(resourceAsStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> sqlList = rootElement.selectNodes("//sql");
        Map<String, MappedStatement> mappedStatementMap = new HashMap<>();
        for (Element element : sqlList) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            String key = namespace + "." + id;
            mappedStatementMap.put(key, mappedStatement);
        }
        configuration.setMappedStatementMap(mappedStatementMap);
    }
}
